<template>
  <div class="chat-container">

    <!-- 登录区域 -->
    <div class="login">
      <button @click="showLogin = true" v-if="!isLoggedIn">登录</button>
      <span v-if="isLoggedIn" class="welcome-text">欢迎，{{ username }}</span>
      <button v-if="isLoggedIn" @click="logout">退出登录</button>
    </div>

    <div class="center-container">
      <!-- 聊天消息区域 -->
      <div class="chat-messages">
        <div
            v-for="(message, index) in messages"
            :key="index"
            class="message"
            :class="message.type === 'ai' ? 'ai-message' : 'user-message'"
        >
          <div class="content">
            {{ message.text }}
            <div v-if="message.loading" class="loading-dots">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <input
            v-model="userInput"
            type="text"
            placeholder="输入您的问题..."
            @keyup.enter="sendMessage"
            :disabled="isLoading || !isLoggedIn"
            @focus="handleInputFocus"
        />
        <button @click="sendMessage" :disabled="isLoading || !isLoggedIn">
          {{ isLoading ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>

    <!-- 登录弹窗 -->
    <div v-if="showLogin" class="modal-overlay" @click.self="showLogin = false">
      <div class="modal">
        <h3>登录</h3>
        <input v-model="loginAccount" placeholder="用户名" />
        <input v-model="loginPassword" type="password" placeholder="密码" />
        <button @click="handleLogin">登录</button>
        <button @click="showRegister = true" v-if="!isLoggedIn">注册</button>
        <button @click="showLogin = false">取消</button>
      </div>
    </div>

    <!-- 注册弹窗 -->
    <div v-if="showRegister" class="modal-overlay" @click.self="showRegister = false">
      <div class="modal">
        <h3>注册</h3>
        <input v-model="registerAccount" placeholder="用户名" />
        <input v-model="registerPassword" type="password" placeholder="密码" />
        <button @click="handleRegister">注册</button>
        <button @click="showRegister = false">取消</button>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const userInput = ref('')
const messages = ref([
  {
    type: 'ai',
    text: '你好！我是AI助手，使用前请登录',
    loading: false
  },

])
const isLoading = ref(false)

// 登录相关状态
const isLoggedIn = ref(false)
const username = ref('')

// 控制弹窗显示
const showLogin = ref(false)
const showRegister = ref(false)

// 登录表单
const loginAccount = ref('')
const loginPassword = ref('')

// 注册表单
const registerAccount = ref('')
const registerPassword = ref('')


const userid = ref('')  // 保存登录用户id


// 处理输入框获得焦点：未登录弹登录框
function handleInputFocus() {
  if (!isLoggedIn.value) {
    showLogin.value = true
    document.activeElement.blur()
  }
}

// 登录接口示例
async function handleLogin() {
  if (!loginAccount.value || !loginPassword.value) {
    alert('请填写用户名和密码')
    return
  }
  try {
    console.log(loginAccount.value+" "+loginPassword.value)
    const res = await axios.post('http://localhost:8080/user/login', {
      user_account: loginAccount.value,
      user_psw: loginPassword.value},
        {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    // 根据后端返回结果调整
    if (res.data === '登录成功' || res.data.code === 200) {
      isLoggedIn.value = true
      username.value = loginAccount.value
      alert('登录成功')
      showLogin.value = false
      userid.value = loginAccount.value

      loginAccount.value = ''
      loginPassword.value = ''
       // 保存userid
      console.log(userid.value)
    } else {
      alert(res.data || '登录失败')
    }
  } catch (err) {
    alert('登录请求失败，请稍后再试')
    console.error(err)
  }
}

// 注册接口示例
async function handleRegister() {
  if (!registerAccount.value || !registerPassword.value) {
    alert('请填写用户名和密码')
    return
  }
  try {
    const res = await axios.post('http://localhost:8080/user/register', {
      user_account: registerAccount.value,
      user_psw: registerPassword.value
    })
    // 根据后端返回结果调整
    if (res.data === '注册成功' || res.data.code === 200) {
      alert('注册成功，请登录')
      showRegister.value = false
      registerAccount.value = ''
      registerPassword.value = ''
    } else {
      alert(res.data || '注册失败')
    }
  } catch (err) {
    alert('注册请求失败，请稍后再试')
    console.error(err)
  }
}

// 退出登录
function logout() {
  isLoggedIn.value = false
  username.value = ''
  userInput.value = ''
  messages.value = [{
    type: 'ai',
    text: '你好！我是AI助手，使用前请登录',
    loading: false
  }]
}

// 发送消息示例
async function sendMessage() {
  const content = userInput.value.trim()
  if (!content || isLoading.value || !isLoggedIn.value) return

  messages.value.push({ type: 'user', text: content })
  const aiMessage = { type: 'ai', text: '', loading: true }
  messages.value.push(aiMessage)

  userInput.value = ''
  isLoading.value = true


  try {
    const response = await fetch(`http://localhost:8080/deepseek/question?prompt=${encodeURIComponent(content)}
    &userid=${encodeURIComponent(userid.value)}`)
    if (!response.ok) throw new Error('请求失败')
    const reader = response.body.getReader()
    const decoder = new TextDecoder()

    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      const chunk = decoder.decode(value, { stream: true })
      aiMessage.text += chunk
      // 滚动到底部
      setTimeout(() => {
        const container = document.querySelector('.chat-messages')
        if (container) container.scrollTop = container.scrollHeight
      }, 0)
    }
  } catch (error) {
    aiMessage.text = '抱歉，请求服务时出错，请稍后再试。'
    console.error(error)
  } finally {
    aiMessage.loading = false
    isLoading.value = false
  }
}
</script>

<style scoped>
.chat-container{
  background: linear-gradient(135deg, #252525 0%, #101010 100%);
}
.login {
  background: #111111;
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  gap: 20px;
}

.login button {
  background: #4e54c8;
  border: none;
  color: white;
  padding: 5px 12px;
  border-radius: 5px;
  cursor: pointer;
}

.login .welcome-text {
  color: #ccc;
  margin-right: 10px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal {
  background: #222;
  padding: 20px;
  border-radius: 8px;
  width: 300px;
  color: white;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.modal input {
  padding: 8px;
  border-radius: 5px;
  border: none;
  outline: none;
  font-size: 14px;
}
.ai-message {
  align-self: flex-start;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.modal button {
  background: #4e54c8;
  border: none;
  color: white;
  padding: 8px 0;
  border-radius: 5px;
  cursor: pointer;
}

.modal button:last-child {
  background: #666;
}
.center-container {
  display: flex;
  flex-direction: column;
  min-width: 500px;
  max-width: 800px;
  margin: 0px 20%;
  height: 100vh;
  background: linear-gradient(135deg, #252525 0%, #101010 100%);
  color: #ffffff;
  font-family: 'Arial', sans-serif;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.loading-dots {
  display: inline-flex;
  align-items: center;
  height: 1em;
}

.loading-dots span {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #fff;
  margin: 0 2px;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

input:disabled {
  opacity: 0.7;
  background: #3a3a3a !important;
}


.message {
  display: flex;
  max-width: 80%;
}


.content {
  padding: 12px 15px;
  border-radius: 18px;
  line-height: 1.4;
}

.ai-message .content {
  background: #2c2c2c;
  border-top-left-radius: 5px;
}

.user-message .content {
  background: #4e54c8;
  border-top-right-radius: 5px;
}

.input-area {
  display: flex;
  padding: 25px;
  background: rgba(30, 30, 30, 0.8);
  border-top: 1px solid #333;
}

.input-area input {
  flex: 1;
  padding: 12px 15px;
  border-radius: 25px;
  border: none;
  background: #2c2c2c;
  color: white;
  font-size: 16px;
  outline: none;
}

.input-area button {
  margin-left: 10px;
  padding: 0 20px;
  border-radius: 25px;
  border: none;
  background: #4e54c8;
  color: white;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.3s;
}

.input-area button:hover {
  background: #4348a8;
}
</style>